package com.wk.auth.service.impl;

import com.wk.auth.config.JwtProperties;
import com.wk.auth.service.AuthService;
import com.wk.common.utils.CookieUtils;
import com.wk.common.utils.JwtUtils;
import com.wk.ums.entity.Member;
import com.wk.ums.feign.MemberFeign;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@Service
@EnableConfigurationProperties(JwtProperties.class)     //启用指定配置类
public class AuthServiceImpl implements AuthService {

    @Autowired
    private MemberFeign memberFeign;

    @Autowired
    private JwtProperties jwtProperties;

    @Override
    public void accredit(String username, String password, HttpServletRequest request, HttpServletResponse response) {
        //查询用户是否存在
        Member member = memberFeign.queryUser(username, password).getData();
        if (member == null) {
            return;
        }

        //生成jwtToken
        try {
            //设置载荷
            Map<String,Object> map = new HashMap<>();
            map.put("id", member.getId());

            //生成token
            String token = JwtUtils.generateToken(map, jwtProperties.getPrivateKey(), jwtProperties.getExpire());
            if (StringUtils.isNotBlank(token)) {
                //token放入到cookie中
                CookieUtils.setCookie(request,response,jwtProperties.getCookieName(),token,jwtProperties.getExpire()*60);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("用户名或密码错误");
        }
    }

}
